

import { ApiFilled, DeleteOutlined, LikeOutlined, MessageOutlined, PlusOutlined, StarOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, Link, useIntl ,useLocation, useParams} from '@umijs/max';
import { Button, Drawer, FloatButton, Form, Input, InputNumber, List, Modal, Space, Switch, Tag, message } from 'antd';
import React, { useRef, useState ,useEffect} from 'react';
//services

import { addPaperUsingPost, deletePaperUsingPost, getPaperByIdUsingGet, listPaperByPageUsingGet, updatePaperUsingPost } from '@/services/backend1/paperController';
import { jsonToQuestionScores, toQuestionVO } from '@/utils/jsonUtil';
import { getQuestionWithAnswerUsingGet, listQuestionByPageUsingGet } from '@/services/question-management/questionController';

// import PaperEditor from '../PaperEditor/PaperEditor';



type QS = {
  question?:API.QuestionVO;
  score?: number;
};

type DrawerDataType= {
  id?: number;
  score?: number;
  chapter?: string;
  difficulty?: number;
  errorProne?: string;
  errorRate?: string;
  knowledgePoint?: string;
  questionContent?: string;
  questionType?: string;
  texture?: string;
};

const PaperEditor: React.FC = () => {

  
  
  //paper detail page
  //paper already added
  const [paperData, setPaperData] = useState<API.Paper>();
  const [qsList,setQsList] =  useState<QS[]>([]);
  const [totalScore,setTotalScore] =  useState<number>(0);

 
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [drawerData,setDrawerData] = useState<DrawerDataType[]>([]);

  //Question ProTable
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Question>();
  const [selectedRowsState, setSelectedRows] = useState<API.Question[]>([]);

  //addOne modal
  const [addModalOpen, handleAddModalOpen] = useState<boolean>(false);
  
  //parse url params :id

  
  const params = useParams();

  const fetchData = async () => {
    try {
      //request and set paper
      const res = await getPaperByIdUsingGet({ id: Number(params.id) });
      const paper = res.data;
      setPaperData(paper);

      setQsList([]);
      //request and set qsList (quesions in paper)
      if (paper && paper.questions) {
        const questionsArray = jsonToQuestionScores(paper.questions);
        let total = 0;
        for (const item of questionsArray) {
          const res = await getQuestionWithAnswerUsingGet({ id: Number(item.id) });
          if(res.code===0) {
            //计算total score
            const score = item.score;
            total += score?score:0;
            // add to qsList
            const newQS: QS = { question: res.data, score: score };
            setQsList(prevList => [...prevList, newQS]);
          }
        }
        //set total score
        setTotalScore(total);
      }
    } catch (error: any) {
      // console.error('Error fetching data: ', error);
      message.error('加载失败！' + error.message);
    }
  };

  useEffect(() => {
    fetchData();
  }, [params.id]);

  // detail page
  const showDrawer = () => {
    setDrawerVisible(true);
  };
  const onCloseDrawer = () => {
    setDrawerVisible(false);
  };

  const handleSaveScore = () => {
    // Save the modified score to selected items
    // form.validateFields().then(values => {
    //   const { score } = values;
    //   const updatedItems = selectedRowsState.map(item => ({
    //     ...item,
    //     score: score,
    //   }));
    //   setSelectedRows(updatedItems);
    //   setDrawerVisible(false);
    // });
  };

  //about drawer 

  useEffect(()=>{
    const data=Array.from(qsList).map((item)=>({
      id: item.question?.id,
      score: item.score,
      questionType: item.question?.questionType,
      questionContent: item.question?.questionContent,
      texture : item.question?.texture,
      knowledgePoint: item.question?.knowledgePoint,
      chapter: item.question?.chapter,
      difficulty: item.question?.difficulty,
      errorProne: item.question?.errorProne,
      errorRate: item.question?.errorRate, 
    }));
    setDrawerData(data);
  },[qsList]);

  


  const IconText = ({ icon, text }: { icon: React.FC; text: string }) => (
    <Space>
      {React.createElement(icon)}
      {text}
    </Space>
  );



  const handleAdd = async(items : API.Question[]) => {
    //add questions to the paper
    // setQsList([...qsList, items]);
    // handleAddModalOpen(false);
    // return true;
  };

  const handleAddOne = async(params: { id: number | undefined, score: number }) => {
    const map: API.QuestionScore[] = qsList.map((item: QS) => ({
      id: item.question?.id,
      score: item.score
    }));
    
    map.push({id: params.id,score: params.score})

    // setQsList([...qsList,]);
    const hide = message.loading('正在添加');
    try { 
      const res = await updatePaperUsingPost({
        id:paperData?.id,
        questions : map,
      });
      // if(res.code!== 0) {
      //   message.error('添加失败,请重试');
      //   return false;
      // }
      fetchData();
      hide(); 
      message.success('添加成功');
      return true;
    } catch (error:any) {
      hide();
      message.error('添加失败,请重试',error.message);
      return false;
    }
  };

  const handleDeleteItem = async (itemId: number|undefined) =>{
    if (itemId === undefined) {
      return; // 如果 itemId 不存在，直接返回
    }

    //reset total score
    const itemToRemove = qsList.find((item) => item.question?.id === itemId);
    let newTotal =0;
    if (itemToRemove && itemToRemove.score !== undefined) { 
      newTotal = totalScore - itemToRemove.score; 
      
    }

    // 过滤掉对应 id 的项
    const updatedQsList = qsList.filter((item) => item.question?.id !== itemId); 
    const updatedMap: API.QuestionScore[] = updatedQsList.map((item: QS) => ({
      id: item.question?.id,
      score: item.score
    }));
    // setQsList([...qsList,]);
    const hide = message.loading('正在删除');
    try { 
      const res = await updatePaperUsingPost({
        id:paperData?.id,
        questions : updatedMap,
      });
      // if(res.code!== 0) {
      //   message.error('删除失败,请重试');
      //   return false;
      // }
      // 更新本地的 qsList , totalScore
      setQsList(updatedQsList); 
      setTotalScore(newTotal);
      // fetchData()
      hide(); 
      message.success('删除成功');
      return true;
    } catch (error:any) {
      hide();
      message.error('删除失败,请重试',error.message);
      return false;
    }
  };
  

  // questions library
  const columns: ProColumns<API.Question>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: '类型',
      dataIndex: 'questionType',
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
      valueEnum: {
        'choose': {
          text: <Tag color={"green"} key={'choose'}>
            {'选择题'}
          </Tag>,
        },
        'blanking': {
          text:  <Tag color={"blue"} key={'blanking'}>
            {'填空题'}
          </Tag>,
        },
        'subjective': {
          text: <Tag color={"red"} key={'subjective'}>
            {'主观题'}
          </Tag>,
        },
      },
    },
    {
      title: '题目内容',
      dataIndex: 'questionContent',
      valueType: 'textarea',
      copyable: true,
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
    },
    {
      title: '知识点',
      dataIndex: 'knowledgePoint',
    },
    {
      title: '章节',
      dataIndex: 'chapter',
    },
    {
      title: '易错点',
      dataIndex: 'errorProne',
      hideInSearch: true,
    },
    {
      title: '难易度',
      dataIndex: 'difficulty',
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
      valueEnum: {
        0: {
          text: '简单',
          status: 'Processing',
        },
        1: {
          text: '普通',
          status: 'Success',
        },
        2: {
          text: '困难',
          status: 'Error',
        },
      },
    },
    {
      title: '错误率',
      dataIndex: 'errorRate',
      hideInSearch: true,
    },
    {
      title: '附图',
      dataIndex: 'texture',
      valueType: 'image',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a 
          onClick={() => {
            handleAddModalOpen(true);
            setCurrentRow(record);
          }} 
          target="_blank" 
          rel="noopener noreferrer" 
          key="view"
        >
          <span>添加</span>
        </a>,
      ],
    },
  ]; // const columns


  return (
    <PageContainer>
      <FloatButton type="primary" style={{ top: '35%' }} 
        tooltip={<div>试卷详情</div>}
        onClick={showDrawer} >
      </FloatButton>

      {/* handleAddModalOpen(true);
          setCurrentRow(record); */}
      <Drawer
        width={600}
        open={drawerVisible}
        closable={false}
        onClose={onCloseDrawer}
      >
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <span style={{ fontWeight: 'bold', marginRight: '10px' }}>{paperData?.name}</span>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ fontWeight: 'bold' }}>总分: </span>
            <a style={{ fontWeight: 600, marginLeft: '5px' }}>{totalScore}</a>
          </div>
        </div>
   
        <List
          itemLayout="vertical"
          size="large"
          rowKey="id"
          dataSource={drawerData}
          // bordered={true}
          renderItem={(item) => (
            <List.Item
              key={item.id}
              actions={[
                <Button type="text" onClick={() => handleDeleteItem(item.id)}>
                  <DeleteOutlined />
                </Button>,
                // <IconText icon={LikeOutlined} text="156" key="list-vertical-like-o" />,
                // <IconText icon={MessageOutlined} text="2" key="list-vertical-message" />,
              ]}
              extra={
                <img
                  width={272}
                  // alt="logo"
                  src={item.texture}
                />
              }
            >
              <List.Item.Meta
                // title={item.questionType}
                description={item.score+'分'}
              />
             {item.questionContent}
            </List.Item>
          )}
        />
{/*         
        <Form form={form} layout="horizontal">
          <Form.Item
            label="分数"
            name="score"
            rules={[{ required: true, message: '请输入分数' }]}
          >
            <InputNumber />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleSaveScore}>保存</Button>
          </Form.Item>
        </Form> */}
      </Drawer>


      <ProTable<API.Question, API.PageParams>
        headerTitle={'题库'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          //null or + NEW 
        ]}
        
        request={
          async (params: { 
            pageSize?: number; 
            current?: number; 
            keyword?: string 
          }) => {
          const res = await listQuestionByPageUsingGet({
            ...params,
          });
          if (res.data) {
            return {
              data: res.data.records || [],
              success: true,
              total: res.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        // 多选复选框
        // rowSelection={{
        //   type: 'checkbox',
        //   onChange: (_, selectedRows) => {
        //     console.log("Selected Rows:", selectedRows);
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />

      {/* // 多选复选框操作逻辑 */}
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              <span>项</span> 
              &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleAdd(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <span>批量添加</span>
          </Button>
        </FooterToolbar>
      )}


      <ModalForm
        title={'设置分值'}
        width="400px"
        open={addModalOpen}
        onOpenChange={(open)=>{
          if(!open) {
            setCurrentRow(undefined);
          }
          handleAddModalOpen(open);
        }}
        initialValues={undefined}
        onFinish={async (value) => {
         
          const updatedRow = {  id:currentRow?.id , score: value.score };
          const success = await handleAddOne(updatedRow);
          if (success) {
            handleAddModalOpen(false);
            // handleLoadDrawerData(true);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '分值是必填项',
            },
          ]}
          width="md"
          name="score"
        />
      </ModalForm>

    </PageContainer>
  );
};


export default PaperEditor;
